package news;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class DBUtil {

	private DBUtil() {
	}

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (Exception e) {
		}
	}
	static String url = "jdbc:mysql://localhost:3306/newsmanagersystem?useSSL=false";

	public static Connection getConnection() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(url, "root", "123456");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	public static Date utilDateFormatsqlDate(String str) {
		java.sql.Date date = null;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		java.util.Date curDate = new java.util.Date();
		try {
			curDate = format.parse(str);
			date = new java.sql.Date(curDate.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	public static void close(PreparedStatement s) {
		if (s != null) {
			try {
				s.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		System.out.println("关闭PreparedStatement");
	}

	public static void close(Connection s) {
		if (s != null) {
			try {
				s.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		System.out.println("关闭Connection");
	}

	public static void close(ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		System.out.println("关闭ResultSet");
	}

	public static void close(ResultSet rs, PreparedStatement ps, Connection c) {
		close(rs);
		close(ps);
		close(c);
	}

	public static int executeUpdate(String sql, Object... args) {
		Connection conn = getConnection();
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				ps.setObject(i + 1, args[i]);
			}
			System.out.println("ps.executeUpdate()");
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(null, ps, conn);
		}
		return 0;
	}
}